import React, {Component} from 'react';
import {
  Layout,
  Menu,
  Breadcrumb,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Popconfirm,
  Card,
  Row,
  Col,
  Button,
  Radio,
  Dropdown,
  Icon,
  Upload,
  message,
  Table,
  Pagination,
  Checkbox
} from 'antd';
import PurchaseModal from './component/purchase_item';
import FilterPanel from './component/purchase_filter';
import moment from 'moment'
import _ from 'underscore'
const FormItem = Form.Item;
const {Header, Content, Footer} = Layout;
import WrapPage from './_wrap'
import styles from './main.less'
import * as PurchaseModel from '../model/purchase';
import * as PayModel from '../model/pay';
import * as ContractModel from '../model/contract';
import * as CustomerModel from '../model/customer';
import * as UserModel from '../model/user';
import * as  StockModel from '../model/stock';
import * as  ProductModel from '../model/product';
import CheckInputList from './component/purchase_check_input_list';
import StockLg from './component/purchase_stock_lg'
import EditPi from './component/purchase_edit_pi'
const config = require('../config');

import * as  InputModel from '../model/input';

let role=JSON.parse(localStorage.user || "{}").role;
 class _Page extends React.Component {
    constructor(props) {
        super(props);
            this.state = {page:1,pageSize:10,orderBy:'createAt',filter:{"status":{$in:['inPurchase','inPay']}},data:{list:[]},visible:false,visible1:false,data1:[]};
            this.updateList()
      }
      async updateList(nstate={}){
            var nstate = Object.assign({},this.state,nstate) //全备份
            let res = await PurchaseModel.fetch({
                filter:nstate.filter,
                orderBy:nstate.orderBy,
                startPos:nstate.pageSize*(nstate.page-1),
                limit:nstate.pageSize
            })
            if(res.status == 'success'){
                nstate.data = res.data;
                for(let purchase of nstate.data.list){
                  res = await ContractModel.getByNum(purchase.contract_num)
                  let contract_product_map = {} //缓存字典  把售价信息追加到stock里
                  if(res.data.item){
                    purchase.contract = res.data.item  //追加合同信息
                    res = await CustomerModel.getByNum(purchase.contract.customer_num)
                    if(res){
                      purchase.contract.customer = res.data.item || {} //追加客户信息
                    }
                    contract_product_map = _.object(purchase.contract.products.map(d=>d.product_num)
                    ,purchase.contract.products)
                  }
                  for(let pd of purchase.products){ //遍历追加商品和到货信息
                    res = await ProductModel.getByNum(pd.product_num)
                    pd.product = res.data.item || {components:[]}
                    res = await StockModel.getByNum(pd.stock_num)
                    pd.stock = res.data.item || {components:[]}
                    if(pd.product.cnum in contract_product_map){
                      for(let k of ['origin_money','discount','contract_money']){
                        pd.stock[k] = contract_product_map[pd.product.cnum][k]
                      }
                    }
                  }
                }
                let data1=nstate.data.list;
                let inputlist=await InputModel.fetch({filter:{status:"input"}});
               let suitcase_num=Array.from(inputlist.data.list||[]).map(s=>s.suitcase_num);
              if(data1.length>0){
                 data1.map(puchase=>puchase.products.map(pd=>pd.stock.components.map(
                    cm=>{
                      if(suitcase_num.findIndex(v=>v==cm.suitcase_num)<0 && cm.suitcase_num!==''){
                        cm.status="等待入库";
                      }else if(suitcase_num.findIndex(v=>v==cm.suitcase_num)>=0){
                        cm.status="已入库";
                      }else{
                        cm.status="请补加提箱单号";
                      }
                    }
                  )));
              }
              nstate.data1=data1;
                this.setState(nstate)
            }else{
                message.error('更新失败')
            }
          }

        filterCallback(filter){
            this.updateList({filter})
        }
        // async return2Father(id,item){ //update or create
        //     // this.updateList({})
        // }
        // async cancel(id){
        //     // console.log('正在取消中');
        // }
        showModel=()=>{
          this.setState({
            visible: true,
          });
        }
         handleOk = (e) => {
          this.setState({
            visible: false,
          });
        }
        handleCancel = (e) => {
          this.setState({
            visible: false,
          });
        }
        // async editList(data=[]){
        //        let res=await InputModel.fetch({filter:{status:"input"}});
        //        let suitcase_num=Array.from(res.data.list||[]).map(s=>s.suitcase_num);
        //       if(data1.length>0){
        //          data.map(puchase=>puchase.products.map(pd=>pd.stock.components.map(
        //             cm=>{
        //               if(suitcase_num.findIndex(v=>v==cm.suitcase_num)<0 && cm.suitcase_num!==''){
        //                 cm.status="等待入库";
        //               }else if(suitcase_num.findIndex(v=>v==cm.suitcase_num)>=0){
        //                 cm.status="已入库";
        //               }else{
        //                 cm.status="请补加提箱单号";
        //               }
        //             }
        //           )));
        //       }
        //       this.setState({data1:data});
        // }
        async changeStatus(id,tag,cnum){
          if(tag=="pay"){
            let to_user = []
            let filter = {'role':{$in:['accountant','accountant_manager']}};
            let users = await UserModel.fetch({
              filter:filter,
              limit:999999,
              startPos: 0,
            })
            users.data.list.map(d=>to_user.push(d.cnum));
            let res=await PurchaseModel.updateById(id,{status:'inPay',to_user:to_user,note:cnum+'采购单审核成功',action:'添加'});
            res.status == 'success' ? '' : message.error('提交失败');
          }else if(tag=="purchase"){
            let res=await PurchaseModel.updateById(id,{status:'cancel'});
            res.status == 'success' ? '' : message.error('作废失败');
          }
          this.updateList()
        }
        inputSuitCase(obj,key){
          // smalltalk.prompt('录入提箱单号', '*', '20').then(function(value) {
          //   obj[key]=v
          //   let data = this.state.data
          //   this.setState({data})
          // }, function() {
          //     console.log('cancel');
          // });
          // dialogs.prompt('username', 'joe.smith@gmail.com', function(ok) {
          //   console.log('prompt with default', ok)
          //
          // })

        }
  render() {
    let filter={}
        let data=this.state.data.list
        const columns = [
            {
              title: <span style={{fontSize:"14px"}}>基本信息</span>,
              dataIndex: 'brand_num',
              key: 'brand_num',
              render: (text,record) =><ul>
                <li>编号：<span>{record.cnum}</span></li>
                <li>品牌：<span>{record.brand_num}</span></li>
                <li>采购币种：<span>{record.currency_num}</span></li>
                <li>采购专员：<span>{record.purchase_user}</span></li>
                <li>采购经理：<span>{record.purchase_master}</span></li>
                <li>合同编号：<span>{record.contract_num}</span></li>
                <li>线下合同编号：<span>{record.contract.offline_num}</span></li>
                <li>客户编号：<span>{record.contract.customer.cnum}</span></li>
                <li>客户姓名：<span>{record.contract.customer.name}</span></li>
                <li>客户地址：<span>{record.contract.customer.address}</span></li>
                <li>提货单号：<span>{record.take_num}</span></li>
                <li>下单日期：<span>{moment(record.order_at).format('YYYY-MM-DD')}</span></li>
              </ul>
            },
            {
              title: <span style={{fontSize:"14px"}}>产品列表</span>,
              dataIndex: 'cnum',
              key: 'cnum',
              render: (text,record) => (
                      <table style={{borderSpacing:"10px"}}>
                        <tbody>
                        <tr>
                        <th>产品</th><th>图片</th><th>产品部件</th>
                        <th>价格</th>
                        <th>到货编号</th><th>产品PI</th><th>到货部件列表</th>
                        </tr>
                        {record.products.map(pd=><tr key={pd.stock_num}>
                          <th>编号:{pd.product_num}<br/>品牌:{pd.product.brand_num}<br/>型号:{pd.product.model}<br/>名字:{pd.product.name}</th>
                          <th><img style={{width:"100px",heigth:"100px"}}
                            src={config.host+'/file/'+pd.product.pic}/></th><th>{pd.product.components.map(cp=><div key={cp.name}>
                              {cp.name} * {cp.quantity}
                            </div>)}</th>
                          <th>原价:{pd.stock.origin_money}元<br/> 折扣:{pd.stock.discount}<br/>合同售价:{pd.stock.contract_money}元</th>
                          <th>{pd.stock.cnum}</th><th>{pd.stock.product_identity||<EditPi updateList={e=>this.updateList()} stock={pd.stock}><Button>添加PI</Button></EditPi>}</th><th>{pd.stock.components.map(cp=><div key={cp.cnum} style={{lineHeight:"18px"}}>
                            {cp.cnum} : {cp.name},提箱单号{cp.suitcase_num||<StockLg updateList={e=>this.updateList()} record={cp} stock={pd.stock}><Button>添加</Button></StockLg>},箱单号{cp.box_order_num},箱号{cp.box_num},箱数{cp.box_quantity}
                          </div>)}</th>
                        </tr>)}
                        </tbody>
                    </table>
              )
            },{
              title: <span style={{fontSize:"14px"}}>操作</span>,
              key: 'operation',
               render: (text, record) => (
                 <span>
                   {
                    record.status !== "cancel"?
                       record.status == 'inPurchase' || role === "buyer_manager" ?
                       <span>
                         <Button onClick={()=>this.changeStatus(record._id,'pay',record.cnum)} style={record.status=="inPay"?{display:'none'}:{display:''}}><Icon type="arrow-right" />申请付款</Button>
                         <Button onClick={()=>this.changeStatus(record._id,'purchase')} style={record.status=="cancel"?{disabled:true}:{disabled:false}} style={role === "buyer_manager" ?{display:""}:{display:"none"}}><Icon type="arrow-right" />作废</Button>
                       </span>
                       : <span>已提交</span>
                     :
                       <span>已作废</span>
                   }
                 </span>
               ),
            }
          ];
    return (
      <WrapPage>
        <div style={{fontSize:"14px"}}>
                   <Row>
                     <Col span={12}>采购订单表(未入库)</Col>
                     <Col span={12}>
                         <Row type="flex" justify="end">
                             <Col>
                               <PurchaseModal record={{}} return2Father={itm=>this.return2Father(null,itm)}>
                                 <Button type="primary"><Icon type="plus" />添加采购单</Button>
                               </PurchaseModal>
                               <CheckInputList data={this.state.data1}>
                                 <Button><Icon type="check-square" />查看已入库</Button>
                               </CheckInputList>
                              </Col>
                         </Row>
                     </Col>
                   </Row>
                   <FilterPanel filter={filter} filterCallback={f=>this.filterCallback(f)}/>
                   <Table columns={columns} dataSource={data}
                       rowKey={record => record.cnum} pagination={false} scroll={{}} style={{fontSize:"14px !important"}}/>
                   <Pagination className="ant-table-pagination"
                     total={this.state.data.count} current={this.state.page} pageSize={this.state.pageSize} showSizeChanger
                     showTotal={(total, range) => `${range[0]}-${range[1]} of ${total} items`}
                     onChange={(page, pageSize)=>{this.updateList({page:page})}}
                     onShowSizeChange={(current, size)=>this.updateList({pageSize:size})}/>
             </div>
      </WrapPage>
    );
  }
}

export default _Page
